package service

import (
	"encoding/json"
	"fmt"
	"github.com/e421083458/golang_common/log"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/models"
	"rock/customer/modules/redisModules"
	"rock/customer/public"
	"sync"
	"time"
)

//

// 连接
var once sync.Once

// 基础数据库
var InstanceDB *gorm.DB

// 业务数据库
var BusinessDB *gorm.DB

//
type Common struct {
}

// unionId 与 userId 映射
func (c *Common) UnionIdToUserId(gc *gin.Context, tx *gorm.DB, unionId string) (data string) {
	// 取缓存
	redisCache := redisModules.ClientRedis.Get(initParam.OVOPrefix + unionId)
	val, err := redisCache.Result()
	if err == nil {
		err = json.Unmarshal([]byte(val), &data)
		if err != nil {
			return
		}
		return
	} else {
		if err != redis.Nil {
			return
		}
	}
	user := dto.UserDetail{}
	err = tx.SetCtx(public.GetGinTraceContext(gc)).Model(&models.WkbUsers{}).Where("union_id = ?", unionId).Scan(user).Error
	if err != nil {
		if err.Error() != gorm.ErrRecordNotFound.Error() {
			log.Error(fmt.Sprintf("【PATH】%v【MYSQL ERROR】%v", gc.Request.URL.Path, err.Error()))
			return
		}
	}
	if user.UserId == 0 {
		return
	}
	// 存缓存
	data = gconv.String(user.UserId)
	err = addRedis(data, initParam.OVOPrefix+unionId, 15*24*time.Hour)
	return
}
